export const KEY = "goodsData";
export let goodObj = {};

//使用localstorage来存储数据
export function setItem(value) {
    var arrStr = localStorage.getItem(KEY) || '[]';
    var arr = JSON.parse(arrStr);
    arr.push(value);
    localStorage.setItem(KEY, JSON.stringify(arr));
}

//从localstorage中获取数据
export function getItem() {
    var arrStr = localStorage.getItem(KEY) || '[]';
    return JSON.parse(arrStr);
}

//从localstorage中移除数据
export function removeItem(goodsid) {
    var arr = getItem();
    for (var i = arr.length - 1; i >= 0; i--) {
        let item = arr[i];
        if (item.id == goodsid) {
            arr.splice(i, 1);
        }
    }
    //将最新的arr结果保存到localstorge中
    localStorage.setItem(KEY, JSON.stringify(arr));
}

//将获取到的数组转换为指定的对象格式如：{88:1}
export function arr2obj() {
    let arr = getItem();
    let result = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        let item = arr[i];
        if (!result[item.id]) {
            result[item.id] = item.count;
        } else {
            result[item.id] = result[item.id] + item.count;
        }
    }
    return result;
}

//更新localstorage中存储的数据
export function updateCount(obj) {
    let arr = getItem();
    if (obj.type == "add") {
        arr.push({id: obj.goodsid, count: 1});//加
    } else {
        for (var i = 0; i < arr.length; i++) {//减
            let item = arr[i];
            if (item.id == obj.goodsid) {
                if (item.count > 1) {
                    console.log(234);
                    item.count = item.count - 1;
                    break;
                } else {
                    //删除对象
                    arr.splice(i, 1);
                    break;
                }
            }
        }
    }
    //将最新的arr结果保存到localstorge中
    localStorage.setItem(KEY, JSON.stringify(arr));
}

//获取到存储在本地的商品总数
export function getTotal() {
    let res = arr2obj();
    let total = 0;
    for (var k in res) {
        total += res[k];
    }
    return res;
}
